<template>
    <div id="app">
        <h3>登录</h3>
        用户名：<input type="text" v-model="form.account"><br>
        密码：<input type="text" v-model="form.password"><br>
        记住我：<input type="checkbox" v-model="form.rememberMe"><br>
        <button @click="login()">登录</button>
        <button @click="logout()">退出系统</button>

        <hr>
        <iframe ref="ssoIframe"
                v-for="(sso,index) in SSO"
                :key="'sso-'+index"
                :src="sso"/>
    </div>
</template>

<script>
  /* eslint-disable */
  import request from './utils/request.js' ;
  import Cookies from 'js-cookie';

  const MAX_AGE = process.env.VUE_APP_REMEMBER_ME_MAX_AGE;

  const REMEMBER_ME_MAX_AGE = process.env.VUE_APP_REMEMBER_ME_MAX_AGE;
  export default {
    name: 'app',
    data() {
      return {
        SSO: process.env.VUE_APP_SSO.split(','),
        form: {
          account: 'admin',
          password: '123456',
          rememberMe: false,
        },
      };
    },
    created() {
    },
    methods: {
      async login() {
        const form = this.form;
        const { status, data } = await request.put('/prms-system/system/login', form);
        if (status === 200 && data) {
          const { code, data: { headAttr, jwt } } = data;
          if (code === '200') {

            if (form.rememberMe) {
              const expires = new Date(new Date().getTime() + MAX_AGE * 60 * 60 * 1000);
              Cookies.set('AUTH_TOKEN', jwt, { expires });
            } else {
              Cookies.set('AUTH_TOKEN', jwt);
            }
            const iframeList = this.$refs['ssoIframe'];
            iframeList.forEach(iframe => {
              iframe.contentWindow.postMessage({
                SIGN: 'login',
                AUTH_REMEMBER_ME: form.rememberMe,
                AUTH_TOKEN: jwt,
              }, iframe.src); // targetOrigin 目标源必须和iframe的一致菜单通信
            });
          }
        }
      },
      logout() {
        const iframeList = this.$refs['ssoIframe'];
        iframeList.forEach(iframe => {
          iframe.contentWindow.postMessage({
            SIGN: 'logout',
          }, iframe.src);
        });
      },
    },
  };
</script>

<style>
    #app {
        font-family: 'Avenir', Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
    }
</style>
